// pages/comment/comment.js
const db =wx.cloud.database();//初始化数据库
Page({

  /**
   * 页面的初始数据
   */
  data: {
    detail: {},
    content:'',//评价内容
    score: 3.5,//评分分数，默认3.5
    images:[],//图片数组
    img:[],//用来渲染的图片数组
    fileIDs:[],//图片存储路径
    movieid:-1,
    actionSheetShow: false,//actionSheet
    dialogShow:false,
    actions: [{
      name: '添加图片',
      subname: '最多9张',
      disabled: false,
    }],
  },
  previewImg(event){//预览大图
    let index = event.currentTarget.dataset.index;
    let img = this.data.img;
    wx.previewImage({
        current: img[index],
        urls: img,
    })
  },
  deleteImg(event){//单独删除
    let _index = event.currentTarget.dataset.index;
    let img = this.data.img;
    img.splice(_index,1);
    var actions= this.data.actions
    if(this.data.img.length>=9){
      actions[0].disabled=true
    }else{
      actions[0].disabled=false
    }
    this.setData({
        img,
        images:this.data.img,
        actions
    })
  },
  onCloseDialog() {
    this.setData({ dialogShow: false });
  },
  showDialog() {
    this.setData({ dialogShow: true });
  },
  onCloseActionSheet() {
    this.setData({ actionSheetShow: false });
  },
  showActionSheet() {
    this.setData({ actionSheetShow: true });
    var actions= this.data.actions
    if(this.data.img.length>=9){
      actions[0].disabled=true
    }else{
      actions[0].disabled=false
    }
    this.setData({ actions })
  },
  onCancelActionSheet(){
    this.setData({ actionSheetShow: false });
  },
  onSelectActionSheet(event) {
    var that = this;
    wx.chooseImage({
      count: 9,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success:res => {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths);
        that.setData({
          images:that.data.images.concat(tempFilePaths)
        });
        console.log(that.data.images);
        that.setData({
          img:that.data.images.slice(0,9)
        })
        console.log(that.data.images.length);
        console.log(that.data.img);
      }
    })
    console.log(event.detail);
  },
  onContentChange:function(event){
    this.setData({
      content:event.detail
    })
  },
  onScoreChange:function(event){
    this.setData({
      score:event.detail
    })
  },
  submit:function(){
    wx.showLoading({
      title:'提交中',
    })
    console.log(this.data.content);
    console.log(this.data.score);
    //上传图片至云存储
    let promiseArr = [];
    console.log(this.data.content);
    console.log(this.data.images.length);
    if(this.data.content=='' && this.data.images.length==0){
      wx.hideLoading();
      wx.showToast({
        duration: 2000,
        icon: 'error',
        title: '未进行任何评价',
      })
    }else{
      for(let i = 0; i < this.data.img.length;i++){
        promiseArr.push(new Promise((resolve, reject) =>{
          let item = this.data.img[i];//每个图片的临时文件路径
          let suffix = /\.\w+$/.exec(item)[0];//正则表达式，返回文件拓展名
          wx.cloud.uploadFile({
            cloudPath: new Date().getTime() + suffix, // 上传至云端的路径
            filePath: item, // 小程序临时文件路径
            success: res => {
              // 返回文件 ID
              console.log(res.fileID)
              this.setData({
                fileIDs:this.data.fileIDs.concat(res.fileID)
              })
              resolve();
            },
            fail: console.error
          })
        }))
      }
      Promise.all(promiseArr).then( res =>{
        db.collection('comment').add({
          data:{
            content:this.data.content,
            score:this.data.score,
            movieid:this.data.movieid,
            fileIDs:this.data.fileIDs,
          }
        }).then(res=>{
          wx.hideLoading();
          this.setData({ dialogShow: true });
          this.setData({
            img : [],
            images:[]
          });
        }).catch(err=>{
          wx.hideLoading();
          wx.showToast({
            duration: 2000,
            icon: 'error',
            title: '提交失败',
          })
        })
      })
    }
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.showLoading({
      title: '加载中',
    })
    this.setData({
      movieid:options.movieid,
    })
    console.log(options);
    wx.request({
      url: `https://frodo.douban.com/api/v2/movie/${options.movieid}?apiKey=054022eaeae0b00e0fc068c0c0a2102a`,
      success(res){
        console.log(res.data);
        that.setData({
          detail:res.data
        });
        wx.hideLoading();
      },
      fail:function(err){
        console.error(err);
        wx.hideLoading();
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})